package com.heima.datasync.service.impl;

import com.google.common.collect.Lists;
import com.heima.common.constants.search.SearchConstants;
import com.heima.common.exception.CustException;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mrchen
 * @date 2022/7/17 9:38
 */
@Service
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    EsService<SearchArticleVO> esService;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult dataInit() {
        // 1. 判断一下指定的索引库是否存在
        boolean b = esService.existIndex(SearchConstants.ARTICLE_INDEX_NAME);
        // 2. 如果索引库存在  删除索引库
        if (b){
            esService.deleteIndex(SearchConstants.ARTICLE_INDEX_NAME);
        }
        // 3. 创建索引库
        esService.createIndex(SearchConstants.ARTICLE_INDEX_MAPPING,SearchConstants.ARTICLE_INDEX_NAME);

        // 4. 从数据库中查询文章数据
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        if (CollectionUtils.isEmpty(allArticles)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据库中不存在文章数据");
        }
        // 5. 将文章数据批量导入到ES索引库中  ApArticle => SearchArticleVO
        //    批量插入:  1000 ~ 5000
        List<List<ApArticle>> partition = Lists.partition(allArticles, 1000);
        for (List<ApArticle> articleList : partition) {
            List<SearchArticleVO> articleVOList = articleList.stream()
                    .map(apArticle -> {
                        SearchArticleVO searchArticleVO = new SearchArticleVO();
                        BeanUtils.copyProperties(apArticle, searchArticleVO);
                        return searchArticleVO;
                    }).collect(Collectors.toList());
            esService.saveBatch(articleVOList,SearchConstants.ARTICLE_INDEX_NAME);
        }
        return ResponseResult.okResult();
    }
}
